<template>
  <el-drawer v-model="drawer" width="500px" @closed="closed">
    <!-- 标题部分 -->
    <template #header>
      <h4>{{ $t('sys.roleAuth') }}</h4>
    </template>
    <template #default>
      <el-form label-width="100px">
        <el-form-item label="">
          <el-tree
            ref="tree"
            :data="permissionTree"
            show-checkbox
            node-key="permissionId"
            :default-expanded-keys="defaultCheckedKeys"
            :default-checked-keys="defaultCheckedKeys"
            :props="{
              children: 'children',
              label: 'name',
            }"
            default-expand-all
            @check="checkTreeNode"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="save">
            {{ $t('operation.save') }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { roleGetAuth, roleGrantAuth } from '@/api/system/role'
import { permissionGetTree } from '@/api/system/permission'
import { ElMessage } from 'element-plus'

let permissionTree = []
onMounted(async () => {
  let { status, data } = await permissionGetTree()
  if (status == 200) {
    permissionTree = data
  }
})

const defaultForm = {
  roleId: '',
  permissionIds: '', // 权限id
}
let formParams = reactive<any>({
  ...defaultForm,
})

let drawer = ref(false)
let edit = ref(false)
let defaultCheckedKeys = ref([])
const tree = ref()
const show = async (roleId) => {
  formParams.roleId = roleId
  let { status, data } = await roleGetAuth({ roleId })
  if (status == 200) {
    drawer.value = true
    let keys = data.map((v) => v.permissionId)

    let except = []
    data.forEach(v => {
      if (v.parentId && v.parentId != 0) {
        except.push(v.parentId)
      }
    })
    
    formParams.permissionIds = [...keys]

    keys = keys.filter(v => except.indexOf(v) == -1)

    await nextTick()
    tree.value.setCheckedKeys(keys)
  }
}

//保存按钮的方法
const save = async () => {
  let result = await roleGrantAuth(formParams)
  if (result.status == 200) {
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
    drawer.value = false
    $emit('callback')
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}
const checkTreeNode = (target, { checkedKeys, halfCheckedKeys }) => {
  console.log('keys', halfCheckedKeys)
  formParams.permissionIds = [...checkedKeys, ...halfCheckedKeys]
}

const closed = () => {
  Object.assign(formParams, defaultForm)
}

//组件内部数据对外关闭的，别人不能访问
//如果想让外部访问需要通过defineExpose方法对外暴露
defineExpose({
  show,
})
//自定义事件的方法
let $emit = defineEmits(['callback'])
</script>
